// pages/number/modify.js
const app = getApp()
import { numberEdit, numberSave, feeQuery } from '../../utils/conf'
import Toast from 'tdesign-miniprogram/toast/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    overlay: false,
    title: '',
    list: {
      'name': '',
      'rental': '',
      'deposit': '',
      'rental_cycle': 1,
      'rental_cycle_type': 'month',
      'ratio': 1,
      'daily_rent': '',
      'water_price': '',
      'electricity_price': '',
    },
    // 年月日选择框
    pickerType: '',
    pickerValue: ['month'],
    pickerArr: [
      { label: '年', value: 'year' },
      { label: '月', value: 'month' },
      { label: '日', value: 'day' },
    ],
    pickerVisible: false,
    feeArr: [],
    weCycleText: '月',
    weCycleValue: ['month'],
    rentalCycleText: '月',
    rentalCycleValue: ['month'],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData(options.id);
    this.getFeeData();
    wx.setNavigationBarTitle({
      title: '房间管理-编辑',
    })
    this.setData({
      title: options.house_name,
    })
  },

  async getData(id) {
    try {
      const res = await app.call({
        path: numberEdit,
        method: 'POST',
        data: { 'id': id }
      });
      const rentalCycleItem = this.data.pickerArr.find(item => item.value === res.data.rental_cycle_type);
      const weCycleItem = this.data.pickerArr.find(item => item.value === res.data.we_cycle_type);
      const setData = {
        list: res.data,
        ...(rentalCycleItem && {
          rentalCycleText: rentalCycleItem.label,
          rentalCycleValue: [rentalCycleItem.value]
        }),
        ...(weCycleItem && {
          weCycleText: weCycleItem.label,
          weCycleValue: [weCycleItem.value]
        })
      };
      this.setData(setData);
    } catch (error) {
      // 添加错误处理逻辑，可以在这里弹出提示或者记录错误
      console.error('获取数据失败:', error);
      this.showToast('获取数据失败', 'error');
    }
  },

  async getFeeData() {
    try {
      const res = await app.call({
        path: feeQuery,
        method: 'GET'
      });
      this.setData({
        feeArr: res.data,
      });
    } catch (error) {
      // 添加错误处理逻辑，可以在这里弹出提示或者记录错误
      console.error('获取其他收费项目失败:', error);
    }
  },

  bindDataChange(e) {
    let { key } = e.currentTarget.dataset;
    // 确保e.detail有value属性，防止运行时错误
    let value = e.detail && e.detail.value || '';
    // 使用扩展运算符创建新的对象，避免直接修改this.data.list
    let newData = { ...this.data.list, [key]: value };
    this.setData({
      list: newData
    });
  },

  verify() {
    const { list } = this.data;
    const baseRequiredFields = {
      name: '房间名',
      rental_cycle: '房租周期',
      rental: '房租',
      deposit: '押金',
      daily_rent: '日租金',
      ratio: '水电倍率',
      water_price: '水费单价',
      electricity_price: '电费单价',
      we_cycle: '其他周期'
    };

    const requiredFields = {
      ...baseRequiredFields,
      ...this.data.feeArr.reduce((acc, element) => {
        if (element?.column_name && element?.column_id) {
          acc[element.column_id] = element.column_name;
        }
        return acc;
      }, {})
    };

    for (const key in requiredFields) {
      if (list[key] === '' || list[key] === null || list[key] === undefined) {
        return { res: false, msg: `${requiredFields[key]}不能为空` };
      }
    }

    return { res: true, msg: '' };
  },

  async bindSave() {
    let verification = this.verify();
    if (!verification.res) {
      this.showToast(verification.msg);
      return;
    }
    this.setData({ overlay: true });
    try {
      const saveResult = await app.call({
        path: numberSave,
        method: 'POST',
        data: this.data.list
      });
      this.setData({ overlay: false });
      let icon = saveResult.code === 1 ? 'success' : 'warning';
      this.showToast(saveResult.msg, icon);
      if (saveResult.code !== 0) {
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 1000);
      }
    } catch (error) {
      this.setData({ overlay: false });
      console.error('保存数据失败:', error);
      this.showToast('保存数据失败', 'error');
    }
  },

  onPickerChange(e) {
    let newData = { ...this.data.list };
    if (this.data.pickerType === 'we') {
      newData['we_cycle_type'] = e.detail.value[0];
      this.setData({
        weCycleText: e.detail.label[0],
        weCycleValue: [e.detail.value[0]],
        pickerVisible: false,
        pickerType: '',
        list: newData
      });
    } else if (this.data.pickerType === 'rental') {
      newData['rental_cycle_type'] = e.detail.value[0];
      this.setData({
        rentalCycleText: e.detail.label[0],
        rentalCycleValue: [e.detail.value[0]],
        pickerVisible: false,
        pickerType: '',
        list: newData
      })
    }
  },
  onSelect(e) {
    if (e.target.dataset.key === 'rental') {
      this.setData({
        pickerVisible: true,
        pickerType: 'rental',
        pickerValue: [this.data.list.rental_cycle_type]
      });
    } else if (e.target.dataset.key === 'we') {
      this.setData({
        pickerVisible: true,
        pickerType: 'we',
        pickerValue: [this.data.list.we_cycle_type]
      });
    }
  },

  showToast(message, theme = 'none') {
    Toast({
      context: this,
      selector: '#t-toast',
      message: message,
      theme: theme
    });
  }
})